package com.qijian.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qijian.common.exception.ServiceException;
import com.qijian.common.utils.StringUtils;
import com.qijian.system.domain.Dept;
import com.qijian.system.mapper.DeptMapper;
import com.qijian.system.service.IDeptService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements IDeptService {
    private final DeptMapper deptMapper;

    /**
     * 根据部门名称模糊查询部门
     *
     * @param deptName 部门名称
     * @return 部门
     */
    @Override
    public List<Dept> listDeptByDeptName(String deptName) {
        //改成精确匹配
        return this.lambdaQuery().eq(Dept::getDeptName, deptName).list();
    }

    /**
     * 根据部门名称模糊查询部门并判断是否只有id部门
     *
     * @param deptName 部门名称
     * @return 部门id
     */
    @Override
    public Long checkOneDeptByDeptName(String deptName) {
        List<Dept> depts = this.listDeptByDeptName(deptName);
        if (CollUtil.isEmpty(depts)) {
            throw new ServiceException("E01:未查到部门");
        }
        if (depts.size() > 1) {
            throw new ServiceException(StringUtils.format("查到多个部门{}，{}等", depts.get(0).getDeptName(), depts.get(1).getDeptName()));
        }
        return depts.get(0).getDeptId();
    }

    @Override
    public Dept getDeptLeader(Long deptId) {

        return deptMapper.getDeptLeader(deptId);
    }
}
